package com.cy.jt.security.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * 默认的用于处理访问被拒绝的异常处理器对象
 *
 */
public class DefaultAccessDeniedExceptionHandler implements AccessDeniedHandler {
    /**
     *
     * @param httpServletRequest 请求对象
     * @param httpServletResponse  响应对象
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException exception) throws IOException, ServletException {
        //方案一:重定向
//        httpServletResponse.sendRedirect("https://www.baidu.com");
        //方案二:假如访问被拒绝了,向客户端响应一个json格式的字符串
            //2.1 设置响应数据的编码
        httpServletResponse.setCharacterEncoding("utf-8");
            //2.2告诉浏览器响应数据的内容类型以及编码
        httpServletResponse.setContentType("application/json;charset=utf-8");
            //2.3获取输出流对象
        PrintWriter out = httpServletResponse.getWriter();
            //2.4封装数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("state:",httpServletResponse.SC_FORBIDDEN);
        map.put("msg:","没有访问权限,请联系管理员");
            //2.4将数据转换为json格式字符串
        String jsonStr = new ObjectMapper().writeValueAsString(map);
        out.println(jsonStr);
        out.flush();
    }
}
